package com.blue.spring.amqp;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class FastJsonMessageConverter extends AbstractMessageConverter
{
	private static final String CHARSET = "UTF-8";

	private static SerializerFeature[] serializer = new SerializerFeature[]
			{SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteClassName};
	private static Feature[] feature = new Feature[] {};
	
	public FastJsonMessageConverter()
	{
	}

	@Override
	protected Message createMessage(Object object, MessageProperties messageProperties)
	{
		byte[] bytes = JSON.toJSONBytes(object, serializer);
		messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
		messageProperties.setContentEncoding(CHARSET);
		if (bytes != null)
		{
			messageProperties.setContentLength(bytes.length);
		}
		return new Message(bytes, messageProperties);
	}

	@Override
	public Object fromMessage(Message message) throws MessageConversionException
	{
		Object obj = JSON.parse(message.getBody(), feature);
		return obj;
	}


}
